'use strict';

const Controller = require('egg').Controller;

class BlogController extends Controller {
    //添加博客
    async create() {
        let {ctx,service} = this;
        //1.接收参数，容错处理
        //2.添加
        let {title,con,username} = ctx.request.body;
        
        if(title && con && username){
            try{
                await service.blog.create(title,con,username);
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //删除博客
    async destroy(){
        let {ctx,service} = this;
        let {id} = ctx.params;
        if(id){
            try{
                await service.blog.destroy(id);
                ctx.body = {
                    code:1,
                    msg:'删除成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //更新博客
    async update(){
        let {ctx,service} = this;
        //1.接收参数，容错处理
        //2.修改
        let {title,con,username} = ctx.request.body;
        let {id} = ctx.params;
        
        if(title && con && username && id){
            try{
                await service.blog.update(title,con,username,id);
                ctx.body = {
                    code:1,
                    msg:'修改成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //查询博客
    async index(){
        let {ctx,service} = this;
        let list = await service.blog.index();
        ctx.body = {
            code:1,
            data:list
        }
    }
    //查看详情
    async show(){
        let {ctx,service} = this;
        let {id} = ctx.params;
        if(id){
            let detail = await service.blog.show(id);
            ctx.body = {
                code:1,
                data:detail
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = BlogController;
